package cn.lili.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.lili.listener.OrderMessageListener;
import cn.lili.modules.order.order.entity.dto.OrderMessage;
import cn.lili.modules.system.client.DictionaryClient;
import cn.lili.modules.system.entity.dos.Dictionary;
import cn.lili.timetask.TimedTaskJobHandler;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 异常业务，订单消息重新执行
 *
 * @author liushuai(liushuai711 @ gmail.com)
 * @version v4.0
 * @Description:
 * @since 2023/4/14 16:39
 */
@RestController
@RequestMapping("/consumer/order")
@Api(tags = "异常订单API")
@RequiredArgsConstructor
@Slf4j
public class OrderMessageRePush {


    private final OrderMessageListener orderMessageListener;
    private final TimedTaskJobHandler timedTaskJobHandler;
    private final DictionaryClient dictionaryClient;
    private final StringRedisTemplate stringRedisTemplate;

    @ApiOperation(value = "订单变更消息")
    @GetMapping("/rePush")
    public void orderChange(OrderMessage orderMessage) {
        orderMessageListener.orderChange(orderMessage);
    }
    @ApiOperation(value = "订单创建")
    @GetMapping("/create")
    public void create(String cartKey) {
        orderMessageListener.orderCreate(cartKey);
    }

    @ApiOperation(value = "执行每日定时任务")
    @GetMapping("/everyDayExecuteJobHandler")
    public void everyDayExecuteJobHandler() {
        timedTaskJobHandler.everyDayExecuteJobHandler(null);
    }

    @ApiOperation(value = "执行分钟定时任务")
    @GetMapping("/everyMinuteExecute")
    public ReturnT<String> everyMinuteExecute() {
        log.info("begin everyDayExecuteJobHandler ");
        return timedTaskJobHandler.everyMinuteExecute(null);
    }

    @GetMapping("/setSendUrl")
    public Object setSendUrl() {
        List<Dictionary> sendCustoms = dictionaryClient.getListByCode("send_customs");
        log.info("sendCustoms == {}", JSONObject.toJSONString(sendCustoms));
        if (CollectionUtil.isEmpty(sendCustoms)) {
            return null;
        }
        List<String> urlList = new ArrayList<>();
        for (Dictionary sendCustom : sendCustoms) {
            //检查路径是否可达，可达加入到。redis请求路径列表中
            boolean domainAvailability = this.checkDomainAvailability(sendCustom.getValueName());
            if (domainAvailability) {
                urlList.add(sendCustom.getValueName());
            }
        }
        log.info("urlList == {}", JSONObject.toJSONString(urlList));
        if (CollectionUtil.isEmpty(urlList)) {
            log.error("海关无可用地址");
        }
        stringRedisTemplate.opsForValue().set("send_customs", String.join(",", urlList));
        log.info("urlList =ddd {}", String.join(",", urlList));
        return stringRedisTemplate.opsForValue().get("send_customs");
    }
    //检查域名能否正常访问
    public boolean checkDomainAvailability(String domain) {
        try {
            HttpRequest httpRequest = HttpUtil.createGet(domain + "/rpc/eport/upload/heartbeat");
            // 设置连接和读取的超时时间
            httpRequest.setConnectionTimeout(1000);
            httpRequest.setReadTimeout(1000);
            String responseBody = httpRequest.execute().body();
            log.info("responseBody == {}", responseBody);
            return "true".equals(responseBody);
        } catch (Exception e) {
            System.out.println("无法连接到域名：" + domain);
        }
        return false;
    }
}
